package com.davesandoval.tpdroid;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import org.acra.ACRA;
import org.acra.annotation.ReportsCrashes;
import org.apache.http.client.ClientProtocolException;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Application;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.text.format.Time;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;

public class AddSOLog extends Activity {
	private String dateSelected;
	private String timeSelected;
	private String newStatus = null;
	private String soReason = null;
	private String soNumber;
	private TextView etStartDate = null;
	private TextView etEndDate = null;
	private TextView etStartTime = null;
	private TextView etEndTime = null;
	private EditText etLogComment;
	private CheckBox cbCopyLog;
	private CheckBox cbCompleteTask;
	private Button btnPostLog;
	private Button btnSaveLog;
	private Calendar startDate;
	private Calendar endDate;
	private Time startTime;
	private Time endTime;
	private TextView tvStart;
	private TextView tvEnd;
	private Spinner spnLogReason;
	private Spinner spnNewStatus;
	private boolean existingLog = false;
	private boolean didpost = false;
	private boolean retainedState = false;

	static final int DATE_DIALOG_ID = 0;
	static final int TIME_DIALOG_ID = 1;

	private TextView activeDateDisplay;
	private TextView activeTimeDisplay;
	private Calendar activeDate;
	private Time activeTime;
	private int mHour;
	private int mMinute;
	private String[] logReasonArray = { " ", "Buds Lock & Key",
			"CONTRACT - On-Site Support", "CONTRACT - Remote Support",
			"Customer Satisfaction - Hours Written Off",
			"Help Desk - Computer Network Support", "Help Desk - IP Telephony",
			"Help Desk - Telephony", "Holiday (NuWave Closed)", "Home Labor",
			"Home Labor - In Shop Flat Rate", "MAC - Computer Network Support",
			"MAC - IP Telephony", "MAC - Telephony Support",
			"Maint - Block Time", "Maint - Computer Network Support",
			"Maint - IP Telephony Support", "Maint - Telephony Support",
			"Office/Other", "Patching", "Project Labor - Computer Network",
			"Project Labor - IP Telephony",
			"Project Labor - Over Budget Hours", "Project Labor - Telephony",
			"Remote - Computer Network Support",
			"Remote - IP Telephony Support", "Remote - Telephony Support",
			"Service - Computer Network Support", "Service - IP Telephony",
			"Service - Telephony Support", "Shipping Charge", "Sick Time",
			"Site Survey - Computer Network", "Site Survey - IP Telephony",
			"Site Survey - Telephony", "Training", "Travel", "Vacation Time",
			"zRepair (DoNotUse)", "zzInstallation Labor (DO NOT USE)" };

	private String[] newStatusArray = { " ", "Completed",
			"Demo/Inventory Movement", "Dispatched", "New", "New Web", "Open",
			"Ordered - Awaiting Arrival", "Ordered-Partially Received",
			"Partially Ordered", "Waiting to be Ordered",
			"zzCustomer Hold (DO NOT USE)" };

	public static Cursor soCursor;
	public static Cursor soLogCursor;
	private String workRequested;
	private String workPerformed;
	private String chargeable;
	private String billable;
	private String copylc;
	private String blntask;
	private String soBlntask;
	private String strRateBasis;
	private String accountNum;
	private AlertDialog soLogAlertDialog;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		CrashReporter cr = new CrashReporter();
		
		setContentView(R.layout.addsolog);
		Bundle extras = getIntent().getExtras();
		soNumber = extras.getString("soNum");
		Main.dbHelper.open();
		soCursor = Main.dbHelper.fetchSOViaSONum(soNumber);
		soLogCursor = Main.dbHelper.fetchSOLogViaSONum(soNumber);
		startManagingCursor(soCursor);
		startManagingCursor(soLogCursor);

		workRequested = soCursor.getString(soCursor
				.getColumnIndex(TPdbAdapter.KEY_BRIEF_DESCRIPTION));
		workPerformed = soCursor.getString(soCursor
				.getColumnIndex(TPdbAdapter.KEY_WORK_PERFORMED));
		accountNum = soCursor.getString(soCursor
				.getColumnIndex(TPdbAdapter.KEY_ACCOUNT_NUMBER));
		soBlntask = soCursor.getString(soCursor
				.getColumnIndex(TPdbAdapter.KEY_SO_BLN_TASK));
		strRateBasis = soCursor.getString(soCursor
				.getColumnIndex(TPdbAdapter.KEY_STRRATEBASIS));

		startDate = Calendar.getInstance();
		endDate = Calendar.getInstance();
		mHour = Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
		mMinute = Calendar.getInstance().get(Calendar.MINUTE);

		tvStart = (TextView) findViewById(R.id.tvStart);
		tvEnd = (TextView) findViewById(R.id.tvEnd);
		etStartDate = (TextView) findViewById(R.id.etStartDate);
		etEndDate = (TextView) findViewById(R.id.etEndDate);
		etStartTime = (TextView) findViewById(R.id.etStartTime);
		etEndTime = (TextView) findViewById(R.id.etEndTime);
		etLogComment = (EditText) findViewById(R.id.etSOLog);
		cbCopyLog = (CheckBox) findViewById(R.id.cbCopyLog);
		cbCompleteTask = (CheckBox) findViewById(R.id.cbCompleteTask);
		btnPostLog = (Button) findViewById(R.id.btnPostLog);
		btnSaveLog = (Button) findViewById(R.id.btnSaveLog);

		spnLogReason = (Spinner) findViewById(R.id.spnLogReason);
		spnNewStatus = (Spinner) findViewById(R.id.spnNewStatus);

		if (soBlntask == "0") {
			cbCompleteTask.setEnabled(false);
		}

		etStartDate.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				showDateDialog(etStartDate, startDate);
			}
		});

		etEndDate.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				showDateDialog(etEndDate, endDate);
			}
		});

		etStartTime.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				showTimeDialog(etStartTime, startTime);
			}
		});

		etEndTime.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				showTimeDialog(etEndTime, endTime);
			}
		});

		btnSaveLog.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Main.dbHelper.open();
				String logDetail = etLogComment.getText().toString();
				chargeable = soReason.startsWith("CONTRACT") ? "1" : "0";
				billable = soReason.startsWith("CONTRACT") ? "0" : "1";
				String copylc = cbCopyLog.isChecked() ? "1" : "0";
				String blntask = "0";
				if (soBlntask == "1") {
					blntask = cbCompleteTask.isChecked() ? "-1" : "0";
				}

				if (Main.dbHelper.soLogExists(soNumber)) {
					Main.dbHelper.updateSOLog(soNumber, logDetail, soReason,
							etStartTime.getText().toString(), etEndTime
									.getText().toString(), etStartDate
									.getText().toString(), etEndDate.getText()
									.toString(), newStatus, chargeable,
							billable, copylc, blntask);
				} else {
					Main.dbHelper.addSOLog(soNumber, logDetail, soReason,
							etStartTime.getText().toString(), etEndTime
									.getText().toString(), etStartDate
									.getText().toString(), etEndDate.getText()
									.toString(), newStatus, chargeable,
							billable, copylc, blntask);
				}
				Main.dbHelper.close();
				AddSOLog.this.finish();
			}
		});

		btnPostLog.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				String formatDate = "dd/MM/yyyy";
				SimpleDateFormat df = new SimpleDateFormat(formatDate);
				Date date1 = null;
				Date date2 = null;
				int time1 = 0;
				int time2 = 0;
				short startampm = 0;
				short endampm = 0;
				try {
					date1 = df.parse(etStartDate.getText().toString());
					date2 = df.parse(etEndDate.getText().toString());
					String start = etStartTime.getText().toString();
					String end = etEndTime.getText().toString();
					if (Integer.parseInt(start.substring(0, 2)) == 12) {
						// Leave the AM/PM alone
					} else if (start.substring(5, 7).equalsIgnoreCase("PM")) {
						startampm = 12;
					} else {
						startampm = 0;
					}
					if (Integer.parseInt(end.substring(0, 2)) == 12) {
						// Leave the AM/PM alone
					} else if (end.substring(5, 7).equalsIgnoreCase("PM")) {
						endampm = 12;
					} else {
						endampm = 0;
					}
					time1 = (Integer.parseInt(start.substring(0, 2)) + startampm)
							* 60 + Integer.parseInt(start.substring(3, 5));
					time2 = (Integer.parseInt(end.substring(0, 2)) + endampm)
							* 60 + Integer.parseInt(end.substring(3, 5));
				} catch (ParseException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				if (date1.after(date2)) {
					Toast.makeText(
							getBaseContext(),
							"Your end date comes before the start date,\nPlease adjust your dates",
							Toast.LENGTH_LONG).show();
				} else if (time1 > time2) {
					Toast.makeText(
							getBaseContext(),
							"Your end time comes before the start time,\nPlease adjust your times",
							Toast.LENGTH_LONG).show();
				} else {
					if (Main.loggedIn) {
						//already logged in
					} else {
						try {
							Main.client.doLogin(Main.globalURI, Main.logid, Main.getPasswd());
						} catch (ClientProtocolException e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						} catch (IOException e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						}
					}
						try {
							String copylc = cbCopyLog.isChecked() ? "1" : "0";
							String blntask = "0";
							if (soBlntask == "1") {
								blntask = cbCompleteTask.isChecked() ? "-1"
										: "0";
							}
							chargeable = soReason.startsWith("CONTRACT") ? "1"
									: "0";
							billable = soReason.startsWith("CONTRACT") ? "0"
									: "1";

							Main.client.putBatchSO(soNumber, newStatus,
									soReason,
									etLogComment.getText().toString(),
									etStartDate.getText().toString(), etEndDate
											.getText().toString(), etStartTime
											.getText().toString(), etEndTime
											.getText().toString(),
									workRequested, workPerformed, chargeable,
									billable, copylc, blntask, accountNum,
									strRateBasis);
							Main.dbHelper.open();
							Main.dbHelper.dropOfflineLogs(soNumber);
							didpost = true;

/*							long result = 0;
							Cursor tempCursor = Main.dbHelper.fetchSOViaSONum(soNumber);
							String soTasks = Main.client.getSOtasks();
							String[] soDetails = Main.client.getSODetail(soNumber);
									String blnTask = "0";
									if (soTasks.contains(soNumber)) {
										blnTask = "1";
									}
									result = Main.dbHelper.updateSO(soNumber, tempCursor.getString(tempCursor
												.getColumnIndex(TPdbAdapter.KEY_ACCOUNT_NAME)), soDetails[0],
											tempCursor.getString(tempCursor
												.getColumnIndex(TPdbAdapter.KEY_PRIORITY)),
											tempCursor.getString(tempCursor.getColumnIndex(
												TPdbAdapter.KEY_REQ_DATE)),
											tempCursor.getString(tempCursor
													.getColumnIndex(TPdbAdapter.KEY_STATUS)),
											tempCursor.getString(tempCursor
													.getColumnIndex(TPdbAdapter.KEY_BRIEF_DESCRIPTION)),
											soDetails[1], soDetails[2], blnTask, soDetails[4]);
*/
							} catch (ClientProtocolException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					/*} else {
						Toast.makeText(
								getBaseContext(),
								"You are not currently logged in;\n\nI am saving this log to the local database.",
								Toast.LENGTH_LONG).show();
						Main.dbHelper.open();
						String logDetail = etLogComment.getText().toString();
						chargeable = soReason.startsWith("CONTRACT") ? "1"
								: "0";
						billable = soReason.startsWith("CONTRACT") ? "0" : "1";
						String copylc = cbCopyLog.isChecked() ? "1" : "0";
						String blntask = cbCompleteTask.isChecked() ? "-1"
								: "0";
						if (existingLog) {
							Main.dbHelper.updateSOLog(soNumber, logDetail,
									soReason, etStartTime.getText().toString(),
									etEndTime.getText().toString(), etStartDate
											.getText().toString(), etEndDate
											.getText().toString(), newStatus,
									chargeable, billable, copylc, blntask);
						} else {
							Main.dbHelper.addSOLog(soNumber, logDetail,
									soReason, etStartTime.getText().toString(),
									etEndTime.getText().toString(), etStartDate
											.getText().toString(), etEndDate
											.getText().toString(), newStatus,
									chargeable, billable, copylc, blntask);
						}
						didpost = false;
					} */
					finish();
				}
			}
		});

		ArrayAdapter<String> reasonAdapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_dropdown_item, logReasonArray);

		spnLogReason.setAdapter(reasonAdapter);
		spnLogReason.setOnItemSelectedListener(new OnItemSelectedListener() {
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				int index = arg0.getSelectedItemPosition();
				soReason = logReasonArray[index];
			}

			public void onNothingSelected(AdapterView<?> arg0) {
				soReason = null;
			}
		});

		ArrayAdapter<String> statusAdapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_dropdown_item, newStatusArray);

		spnNewStatus.setAdapter(statusAdapter);
		spnNewStatus.setOnItemSelectedListener(new OnItemSelectedListener() {
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				int index = arg0.getSelectedItemPosition();
				newStatus = newStatusArray[index];
			}

			public void onNothingSelected(AdapterView<?> arg0) {
				newStatus = null;
			}
		});
		
		updateDisplay(etStartDate, startDate);
		updateDisplay(etEndDate, endDate);
		updateTimeDisplay(etStartTime, activeTime);
		updateTimeDisplay(etEndTime, activeTime);

		soLogAlertDialog = new AlertDialog.Builder(AddSOLog.this).create();
		soLogAlertDialog
				.setMessage("This will cancel the current log.\n\nPress OK to quit, Cancel to return.");
		soLogAlertDialog.setTitle("Cancel Log?");
		soLogAlertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "OK",
				new AlertDialog.OnClickListener() {

					public void onClick(DialogInterface dialog, int which) {
						Main.dbHelper.dropOfflineLogs(soNumber);
						AddSOLog.this.finish();
					}
				});
		soLogAlertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, "Cancel",
				new AlertDialog.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
					}
				});

		if(savedInstanceState!=null) {
            restoreProgress(savedInstanceState);
        }

	} // ---- End onCreate ------

	private OnDateSetListener dateSetListener = new OnDateSetListener() {
		// @Override
		public void onDateSet(DatePicker view, int year, int monthOfYear,
				int dayOfMonth) {
			activeDate.set(Calendar.YEAR, year);
			activeDate.set(Calendar.MONTH, monthOfYear);
			activeDate.set(Calendar.DAY_OF_MONTH, dayOfMonth);
			updateDisplay(activeDateDisplay, activeDate);
			unregisterDateDisplay();
		}
	};

	private OnTimeSetListener timeSetListener = new OnTimeSetListener() {
		public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
			mHour = hourOfDay;
			mMinute = minute;
			updateTimeDisplay(activeTimeDisplay, activeTime);
			unregisterTimeDisplay();
		}
	};

	private void unregisterDateDisplay() {
		activeDateDisplay = null;
		activeDate = null;
	}

	private void unregisterTimeDisplay() {
		activeTimeDisplay = null;
		activeTime = null;
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DATE_DIALOG_ID:
			return new DatePickerDialog(this, dateSetListener,
					activeDate.get(Calendar.YEAR),
					activeDate.get(Calendar.MONTH),
					activeDate.get(Calendar.DAY_OF_MONTH));
		case TIME_DIALOG_ID:
			return new TimePickerDialog(this, timeSetListener, mHour, mMinute,
					false);
		}
		return null;
	}

	@Override
	protected void onPrepareDialog(int id, Dialog dialog) {
		System.out.println("------ onPrepareDialog------");
		super.onPrepareDialog(id, dialog);
		switch (id) {
		case DATE_DIALOG_ID:
			((DatePickerDialog) dialog).updateDate(
					activeDate.get(Calendar.YEAR),
					activeDate.get(Calendar.MONTH),
					activeDate.get(Calendar.DAY_OF_MONTH));
			break;
		case TIME_DIALOG_ID:
			((TimePickerDialog) dialog).updateTime(mHour, mMinute);
			break;
		}
	}

	@Override
	public void onBackPressed() {
		AddSOLog.this.soLogAlertDialog.show();
	}

	@Override
	protected void onPause() {
		System.out.println("----------AddSOLog onPause----------");
		if (!didpost) {
			/*
			Main.dbHelper.open(); chargeable =
			soReason.startsWith("CONTRACT") ? "1" : "0"; billable =
			soReason.startsWith("CONTRACT") ? "0" : "1"; String copylc =
			cbCopyLog.isChecked() ? "1" : "0"; String blntask =
			cbCompleteTask.isChecked() ? "-1" : "0";
			Main.dbHelper.addSOLog(soNumber,
			etLogComment.getText().toString(), soReason,
			etStartTime.getText().toString(), etEndTime.getText()
			.toString(), etStartDate.getText().toString(),
			etEndDate.getText().toString(), newStatus, chargeable, billable,
			copylc, blntask); stopManagingCursor(soCursor);
			stopManagingCursor(soLogCursor);
		*/
		}
		super.onPause();
	}

	@Override
	protected void onResume() {
		System.out.println("----------AddSOLog onResume----------");
		if (!retainedState) {
			Bundle extras = getIntent().getExtras();
			final String soNumber = extras.getString("soNum");
			startManagingCursor(soCursor);
			startManagingCursor(soLogCursor);
			if (Main.dbHelper.soLogExists(soNumber)) {
				soLogCursor = Main.dbHelper.fetchSOLogViaSONum(soNumber);
				existingLog = true;
				etStartTime.setText(soLogCursor.getString(soLogCursor
						.getColumnIndex(TPdbAdapter.KEY_START_TIME)));
				etEndTime.setText(soLogCursor.getString(soLogCursor
						.getColumnIndex(TPdbAdapter.KEY_END_TIME)));
				etStartDate.setText(soLogCursor.getString(soLogCursor
						.getColumnIndex(TPdbAdapter.KEY_START_DATE)));
				etEndDate.setText(soLogCursor.getString(soLogCursor
						.getColumnIndex(TPdbAdapter.KEY_END_DATE)));
				etLogComment.setText(soLogCursor.getString(soLogCursor
						.getColumnIndex(TPdbAdapter.KEY_LOG_DETAIL)));

				for (int i = 0; i < logReasonArray.length; i++) { // logReasonArray;
					if (soLogCursor.getString(
							soLogCursor
									.getColumnIndex(TPdbAdapter.KEY_SO_REASON))
							.equals(logReasonArray[i])) {
						spnLogReason.setSelection(i);
						break;
					}
				}
				for (int i = 0; i < logReasonArray.length; i++) { // newStatusArray
					if (soLogCursor
							.getString(
									soLogCursor
											.getColumnIndex(TPdbAdapter.KEY_NEW_STATUS))
							.equals(newStatusArray[i])) {
						spnNewStatus.setSelection(i);
						break;
					}
				}
			}
		}
		super.onResume();
	}

	public void showTimeDialog(TextView timeDisplay, Time time) {
		System.out.println("------ showTimeDialog------");
		activeTimeDisplay = timeDisplay;
		activeTime = time;
		showDialog(TIME_DIALOG_ID);
	}

	public void showDateDialog(TextView dateDisplay, Calendar date) {
		activeDateDisplay = dateDisplay;
		activeDate = date;
		showDialog(DATE_DIALOG_ID);
	}

	private void updateDisplay(TextView dateDisplay, Calendar date) {
		dateDisplay.setText(new StringBuilder()
				// Month is 0 based so add 1
				.append(date.get(Calendar.MONTH) + 1).append("/")
				.append(date.get(Calendar.DAY_OF_MONTH)).append("/")
				.append(date.get(Calendar.YEAR)));
	}

	private void updateTimeDisplay(TextView timeDisplay, Time time) {
		String ampm;
		String tempTime;
		int tempHour = (mHour > 12) ? mHour - 12 : mHour;
		if (mHour < 12) {
			ampm = "AM";
		} else {
			ampm = "PM";
		}
		tempTime = pad(tempHour) + ":" + pad(mMinute) + ampm;
		timeDisplay.setText(tempTime);
	}

	private static String pad(int c) {
		if (c >= 10)
			return String.valueOf(c);
		else
			return "0" + String.valueOf(c);
	}

	@Override
	protected void onSaveInstanceState(Bundle saveState){
		System.out.println("------ onSaveInstanceState------");
		retainedState = true;
		String sTime = etStartTime.getText().toString();
		String eTime = etEndTime.getText().toString();
		String sDate = etStartDate.getText().toString();
		String eDate = etEndDate.getText().toString();
		saveState.putString("sTime", sTime);
		saveState.putString("eTime", eTime);
		saveState.putString("sDate", sDate);
		saveState.putString("eDate", eDate);
		super.onSaveInstanceState(saveState);
	}

	private void restoreProgress(Bundle savedInstanceState) {
		String sTime = savedInstanceState.getString("sTime");
		String eTime = savedInstanceState.getString("eTime");
		String sDate = savedInstanceState.getString("sDate");
		String eDate = savedInstanceState.getString("eDate");
		etStartTime.setText(sTime);
		etEndTime.setText(eTime);
		etStartDate.setText(sDate);
		etEndDate.setText(eDate);
	}

	@Override
	protected void onStop() {
		stopManagingCursor(soCursor);
		stopManagingCursor(soLogCursor);
		super.onStop();
	}

	@ReportsCrashes(formKey = "dGJMVTJ2ejlhbGotVjhZRTdTYlhzaXc6MQ") 
    public class CrashReporter extends Application {
    	
        @Override
        public void onCreate() {
            // The following line triggers the initialization of ACRA
            ACRA.init(this);
            super.onCreate();
        }
    }
} // ---- End AddSOLog.java -----